package com.frontop.terminal.vlcjplayer.view.main;

import com.frontop.terminal.vlcjplayer.view.AbstractOnDemandMenu;
import com.frontop.terminal.vlcjplayer.view.action.mediaplayer.AudioDeviceActionAbstractMediaPlayerAction;
import uk.co.caprica.vlcj.player.base.AudioDevice;
import uk.co.caprica.vlcj.player.base.MediaPlayer;

import javax.swing.*;
import java.awt.*;

import static com.frontop.terminal.vlcjplayer.Application.application;
import static com.frontop.terminal.vlcjplayer.view.action.Resource.resource;

/**
 * @author Guodong
 */
public final class AudioDeviceMenuAbstract extends AbstractOnDemandMenu {

    private static final String KEY_AUDIO_DEVICE = "audio-device";

    public AudioDeviceMenuAbstract() {
        super(resource("menu.audio.item.device"));
    }

    @Override
    protected void onCreateMenu(JMenu menu) {
        MediaPlayer mediaPlayer = application().mediaPlayer();
        ButtonGroup buttonGroup = new ButtonGroup();
        for (AudioDevice audioDevice : mediaPlayer.audio().outputDevices()) {
            JRadioButtonMenuItem menuItem = new JRadioButtonMenuItem(new AudioDeviceActionAbstractMediaPlayerAction(audioDevice));
            menuItem.putClientProperty(KEY_AUDIO_DEVICE, audioDevice);
            buttonGroup.add(menuItem);
            menu.add(menuItem);
        }
    }

    @Override
    protected void onPrepareMenu(JMenu menu) {
        String audioDeviceId = application().mediaPlayer().audio().outputDevice();
        for (Component c : menu.getMenuComponents()) {
            JRadioButtonMenuItem menuItem = (JRadioButtonMenuItem) c;
            AudioDevice audioDevice = (AudioDevice) menuItem.getClientProperty(KEY_AUDIO_DEVICE);
            if (audioDevice.getDeviceId().equals(audioDeviceId)) {
                menuItem.setSelected(true);
                break;
            }
        }
    }
}
